package com.shigen.demo.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.shigen.demo.annation.Sensitive;
import com.shigen.demo.enums.SensitiveStrategyEnum;
import java.io.IOException;
import java.util.Objects;

/**
 * @author shigenfu
 * @date 2023/10/29 13:46
 */
public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveStrategyEnum strategy;
    private int start;
    private int end;

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException {
        String desensitizedValue;
        if (start >= 0 && end >= 0 && end >= start && end <= s.length()) {
            desensitizedValue = strategy.desensitize(s, start, end);
        } else {
            desensitizedValue = strategy.desensitize(s);
        }
        jsonGenerator.writeString(desensitizedValue);
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        Sensitive annotation = beanProperty.getAnnotation(Sensitive.class);
        if (Objects.nonNull(annotation) && Objects.equals(String.class, beanProperty.getType().getRawClass())) {
            this.strategy = annotation.strategy();
            this.start = annotation.start();
            this.end = annotation.end();
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }
}


